package com.usernet.product.server;

import javax.servlet.http.HttpServletRequest;

import com.usernet.product.dao.UserDao;
import com.usernet.product.entity.Users;

public class UserService {

	private UserDao userDao = new UserDao();

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param tel
	 * @return
	 */
	public String login(HttpServletRequest request) {
		String ret = null;
		try {
			String loginName = request.getParameter("loginName");
			String password = request.getParameter("password");
			int code = userDao.login(loginName, password);

			if (code == -1) {
				ret = MarketUtils.getErrorJson("用户名或邮箱不存在");
			} else if (code == -2) {
				ret = MarketUtils.getErrorJson("密码错误");
			} else if (code == -3) {
				ret = MarketUtils.getErrorJson("用户已被锁定");
			} else if (code == -4) {
				ret = MarketUtils.getErrorJson("服务器异常");
			} else {
				// 登录成功
				Users user = (Users) userDao.getById(Users.class, code);
				StringBuffer buf = new StringBuffer();
				buf.append("{id:");
				buf.append(code);
				buf.append(",niceName:\"");
				buf.append(user.getNiceName());
				buf.append("\",loginName:\"");
				buf.append(user.getLoginName());
				buf.append("\",email:\"");
				buf.append(user.getEmail());
				buf.append("\"}");
				ret = MarketUtils.getResJson(buf.toString());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			ret = MarketUtils.getThrowJson();
		}
		return ret;
	}

	/**
	 * 用户注册
	 * 
	 * @param request
	 * @param tel
	 * @return
	 */
	public String reg(HttpServletRequest request) {
		String ret = null;
		try {
			String tel = MarketUtils.getIpAddr(request);
			final String loginName = request.getParameter("loginName");
			final String password = request.getParameter("password");
			final String email = request.getParameter("email");
			final String niceName = request.getParameter("niceName");
			int code = userDao.reg(loginName, password, email, tel, niceName);

			if (code == -1) {
				ret = MarketUtils.getErrorJson("用户名已存在");
			} else if (code == -2) {
				ret = MarketUtils.getErrorJson("邮箱已存在");
			} else if (code == -3) {
				ret = MarketUtils.getErrorJson("昵称已存在");
			} else if (code == -4) {
				ret = MarketUtils.getErrorJson("服务器异常");
			} else {
				// 注册成功
				ret = MarketUtils.getResJson("\"注册成功\"");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			ret = MarketUtils.getThrowJson();
		}
		return ret;
	}

}
